<template>
  <div class="commodity-detail base-page-container">
    <div class="commodity-detail-header">
      <div class="title-box">{{ pageTitle }}</div>
    </div>
    <div class="content-wrapper">
      <!-- 搜索区域 -->
      <el-form :inline="true" :model="searchForm" :rules="searchRules" ref="searchFormRef" class="search-form"
               label-width="80px">
        <el-form-item label="商品编号" prop="code" required>
          <el-input
              v-model="searchForm.code"
              placeholder="请输入商品编号"
              clearable
              :disabled="isView"
              style="width: 190px">
          </el-input>
        </el-form-item>

        <el-form-item label="商品名称" prop="name" required>
          <el-input
              v-model="searchForm.name"
              placeholder="请输入商品名称"
              clearable
              :disabled="isView"
              style="width: 190px">
          </el-input>
        </el-form-item>

        <el-form-item label="商品条码" prop="barcode" required>
          <el-input
              v-model="searchForm.barcode"
              placeholder="请输入商品条码"
              clearable
              :disabled="isView"
              style="width: 190px">
          </el-input>
        </el-form-item>

        <el-form-item label="分类">
          <el-select
              v-model="searchForm.category"
              placeholder="请选择分类"
              clearable
              :disabled="isView"
              style="width: 190px">
            <el-option
                v-for="option in categoryOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="货主" prop="owner" required>
          <el-select
              v-model="searchForm.owner"
              placeholder="请选择货主"
              clearable
              :disabled="isView"
              style="width: 190px">
            <el-option
                v-for="option in ownerOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="类型" prop="type" required>
          <el-select
              v-model="searchForm.type"
              placeholder="请选择类型"
              clearable
              :disabled="isView"
              style="width: 190px">
            <el-option
                v-for="option in typeOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="品牌" v-show="false">
          <el-select
              v-model="searchForm.brand"
              placeholder="请选择品牌"
              clearable
              style="width: 190px">
            <el-option
                v-for="option in brandOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="单位" prop="unit" required>
          <el-select
              v-model="searchForm.unit"
              placeholder="请选择单位"
              clearable
              :disabled="isView"
              style="width: 190px">
            <el-option
                v-for="option in unitOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="辅助单位">
          <el-select
              v-model="searchForm.auxiliaryUnit"
              placeholder="请选择辅助单位"
              clearable
              :disabled="isView"
              style="width: 190px">
            <el-option
                v-for="option in auxiliaryUnitOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="ABC分类" v-show="false">
          <el-select
              v-model="searchForm.abcCategory"
              placeholder="请选择ABC分类"
              clearable
              style="width: 190px">
            <el-option
                v-for="option in abcCategoryOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="商品标签" v-show="false">
          <el-select
              v-model="searchForm.tag"
              placeholder="请选择商品标签"
              clearable
              style="width: 190px">
            <el-option
                v-for="option in tagOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="存储方式" prop="storageType" required>
          <el-select
              v-model="searchForm.storageType"
              placeholder="请选择存储方式"
              clearable
              :disabled="isView"
              style="width: 190px">
            <el-option
                v-for="option in storageTypeOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
              v-model="searchForm.remark"
              placeholder="请输入备注信息"
              clearable
              :disabled="isView"
              style="width: 600px">
          </el-input>
        </el-form-item>
      </el-form>

      <!-- 表格区域 -->
      <div v-show="false" style="height: 250px;display: flex;flex-direction: column">
        <el-button type="primary" style="width: 70px;margin-bottom: -15px" size="small">
          新增规格
        </el-button>
        <custom-table
            :data="tableData"
            :columns="tableColumns"
            :loading="tableLoading"
            :current-page="pagination.currentPage"
            :page-size="pagination.pageSize"
            :total="pagination.total"
            :showPagination="false"
            :showCustomColumnBtn="false"
            :tableHeight="200"
        >
          <!-- 状态列的自定义插槽 -->
          <template #status="{ row }">
            <el-tag :type="row.status === '启用' ? 'success' : 'info'">
              {{ row.status }}
            </el-tag>
          </template>

          <!-- 操作列 -->
          <template #operation="{ row }">
            <theme-button link @click="handleDelete(row)">删除</theme-button>
          </template>
        </custom-table>
      </div>
      <!-- 表单区域 -->
      <el-divider style="margin:15px 0 20px 0"/>
      <div class="form-container">
        <el-form :model="formData" label-width="100px">
          <el-row :gutter="10">
            <el-col :span="24" style="display: flex;align-items: center;">
              <el-form-item label="批次管理">
                <el-checkbox v-model="formData.batchManagement" :disabled="isView">启用</el-checkbox>
              </el-form-item>
              <el-form-item label="保质期">
                <el-input style="width: 165px;" v-model="formData.shelfLife" :disabled="isView">
                  <template #append>
                    <el-select style="width: 45px" v-model="formData.shelfLifeUnit" placeholder="选择单位" :disabled="isView">
                      <el-option label="天" value="day"/>
                      <el-option label="周" value="week"/>
                      <el-option label="月" value="month"/>
                      <el-option label="年" value="year"/>
                    </el-select>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="临期提醒">
                <el-input style="width: 165px;" v-model="formData.expiryReminder" :disabled="isView">
                  <template #append>
                    <el-select style="width: 45px" v-model="formData.expiryReminderUnit" placeholder="选择单位" :disabled="isView">
                      <el-option label="天" value="day"/>
                      <el-option label="周" value="week"/>
                      <el-option label="月" value="month"/>
                      <el-option label="年" value="year"/>
                    </el-select>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="禁售天数">
                <el-input style="width: 165px;" v-model="formData.noSaleDays" :disabled="isView">
                  <template #append>
                    <el-select style="width: 45px" v-model="formData.noSaleDaysUnit" placeholder="选择单位" :disabled="isView">
                      <el-option label="天" value="day"/>
                      <el-option label="周" value="week"/>
                      <el-option label="月" value="month"/>
                      <el-option label="年" value="year"/>
                    </el-select>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="序列号管理">
                <el-checkbox v-model="formData.serialManagement" :disabled="isView">启用</el-checkbox>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="24">
              <el-form-item label="库存预警上限">
                <el-checkbox v-model="formData.upperLimitFixed" :disabled="isView">固定值</el-checkbox>
                <el-input v-model="formData.upperLimit" style="width: 120px; margin: 0 10px" :disabled="isView"/>
                <el-checkbox v-model="formData.upperLimitUnlimited" :disabled="isView">不限</el-checkbox>
                <el-checkbox style="margin-left: 50px" v-model="formData.upperLimitCanStore" :disabled="isView">可用库存不高于</el-checkbox>
                <el-input v-model="formData.upperLimitDays" style="width: 120px;margin:0 10px" :disabled="isView"/>
                <span>天的销售量并可用库存不高于</span>
                <el-input v-model="formData.upperLimitDays1" style="width: 120px;margin-left: 10px" :disabled="isView"/>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="10">
            <el-col :span="24">
              <el-form-item label="库存预警下限">
                <el-checkbox v-model="formData.lowerLimitFixed" :disabled="isView">固定值</el-checkbox>
                <el-input v-model="formData.lowerLimit" style="width: 120px; margin: 0 10px" :disabled="isView"/>
                <el-checkbox v-model="formData.lowerLimitUnlimited" :disabled="isView">不限</el-checkbox>
                <el-checkbox style="margin-left: 50px" v-model="formData.lowerLimitCanStore" :disabled="isView">可用库存不存子</el-checkbox>
                <el-input v-model="formData.lowerLimitDays" style="width: 120px;margin:0 10px" :disabled="isView"/>
                <span>天的销售量并可用库存不低于</span>
                <el-input v-model="formData.lowerLimitDays1" style="width: 120px; margin-left: 10px" :disabled="isView"/>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 图片上传区域 -->
          <el-divider style="margin:15px 0 20px 0"/>
          <el-row>
            <el-col :span="24">
              <el-form-item label="图片上传">
                <el-upload
                    action="#"
                    list-type="picture-card"
                    :auto-upload="false"
                    :limit="3"
                    :on-preview="handlePictureCardPreview"
                    :disabled="isView"
                >
                  <el-icon>
                    <Plus/>
                  </el-icon>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-divider style="margin:15px 0 30px 0"/>
          <el-row>
            <el-col v-for="(_, index) in 20" :span="6">
              <el-form-item :label="'自定义' + (index+1)">
                <el-input v-model="formData['custom' + index]" style="width: 170px; margin: 0 10px" :disabled="isView"/>
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 按钮区域 -->
          <el-row>
            <el-col :span="24">
              <div class="button-container">
                <template v-if="!isView">
                  <el-button type="primary" @click="handleSave">保存</el-button>
                  <el-button @click="handleCancel">取消</el-button>
                </template>
                <template v-else>
                  <el-button @click="handleEdit" type="primary">编辑</el-button>
                  <el-button @click="handleCancel">返回</el-button>
                </template>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </div>
    <el-image-viewer
        v-if="imgVisible"
        :url-list="[dialogImageUrl]"
        show-progress
        @close="imgVisible = false"
    />
  </div>
</template>

<script setup>
import {ref, reactive, computed} from 'vue'
import {useRoute, useRouter} from 'vue-router'
import {Plus, Setting} from '@element-plus/icons-vue'
import {ElMessage} from 'element-plus'

const route = useRoute()
const router = useRouter()

// 页面状态
const pageMode = ref('add') // 'add' | 'edit' | 'view'

// 计算属性
const isView = computed(() => pageMode.value === 'view')
const pageTitle = computed(() => {
  switch (pageMode.value) {
    case 'add':
      return '新增商品信息'
    case 'edit':
      return '编辑商品信息'
    case 'view':
      return '查看商品信息'
    default:
      return '商品信息'
  }
})

// 初始化页面模式
const initPageMode = () => {
  const mode = route.query.mode
  if (mode && ['add', 'edit', 'view'].includes(mode)) {
    pageMode.value = mode
  }

  // // 如果是编辑或查看模式，需要加载数据
  // if (mode === 'edit' || mode === 'view') {
  //   const id = route.query.id
  //   if (id) {
  //     loadData(id)
  //   }
  // }
}

// 加载数据
const loadData = async (id) => {
  try {
    // 这里添加获取数据的接口调用
    // const res = await api.getCommodityDetail(id)
    // if (res.success) {
    //   searchForm.value = res.data
    // }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  }
}

// 编辑按钮处理
const handleEdit = () => {
  pageMode.value = 'edit'
}

// 搜索表单数据
const searchForm = reactive({
  code: '',
  name: '',
  barcode: '',
  category: '',
  owner: '',
  type: '成品',
  brand: '',
  unit: '',
  auxiliaryUnit: '',
  abcCategory: '',
  tag: '',
  storageType: '',
  remark: ''
})

// 各个下拉框的选项数据
const categoryOptions = [
  {label: '成品', value: '成品'}
]
const ownerOptions = [
  {label: '', value: ''}
]
const typeOptions = [
  {label: '成品', value: '成品'}
]
const brandOptions = []
const unitOptions = []
const auxiliaryUnitOptions = []
const abcCategoryOptions = []
const tagOptions = []
const storageTypeOptions = [
  {label: '常温', value: '常温'},
  {label: '冷藏', value: '冷藏'},
  {label: '冷冻', value: '冷冻'},
  {label: '恒温', value: '恒温'}
]


// 表单数据
const formData = reactive({
  batchManagement: false,
  shelfLife: '',
  shelfLifeUnit: 'day',
  expiryReminder: '',
  expiryReminderUnit: 'day',
  noSaleDays: '',
  noSaleDaysUnit: 'day',
  serialManagement: false,
  upperLimitFixed: false,
  upperLimit: '',
  upperLimitUnlimited: false,
  upperLimitCanStore: false,
  upperLimitDays: '',
  lowerLimitFixed: false,
  lowerLimit: '',
  lowerLimitUnlimited: false,
  lowerLimitCanStore: false,
  lowerLimitDays: ''
})

// 添加表单验证规则
const searchRules = {
  code: [{required: true, message: '请输入商品编号', trigger: 'blur'}],
  name: [{required: true, message: '请输入商品名称', trigger: 'blur'}],
  barcode: [{required: true, message: '请输入商品条码', trigger: 'blur'}],
  owner: [{required: true, message: '请选择货主', trigger: 'change'}],
  type: [{required: true, message: '请选择类型', trigger: 'change'}],
  unit: [{required: true, message: '请选择单位', trigger: 'change'}],
  storageType: [{required: true, message: '请选择存储方式', trigger: 'change'}]
}

// 添加表单引用
const searchFormRef = ref(null)

// 保存事件
const handleSave = () => {
  searchFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        // 这里添加保存数据的接口调用
        // const res = await api.saveCommodity(searchForm.value)
        // if (res.success) {
        ElMessage.success('保存成功')
        router.back()
        // }
      } catch (error) {
        console.error('保存失败:', error)
        ElMessage.error('保存失败')
      }
    } else {
      ElMessage.error('请填写必填项')
      return false
    }
  })
}

// 取消事件
const handleCancel = () => {
  router.back()
}

// 处理单位变化时的默认值设置
const handleShelfLifeUnitChange = (unit) => {
  if (!formData.shelfLife) {
    switch (unit) {
      case 'week':
        formData.shelfLife = '7'
        break
      case 'month':
        formData.shelfLife = '30'
        break
      case 'year':
        formData.shelfLife = '365'
        break
    }
  }
}

// 表格数据
const tableData = ref([
  {
    id: 1,
    code: 'GYS11011',
    name: '供应商A',
    owner: '货主A',
    status: '启用',
    contactPerson: '王阳明',
    contactPhone: '13587584785',
    contactAddress: '浙江省杭州市西湖区西湖大道XX路',
    remark: ''
  },
  {
    id: 1,
    code: 'GYS11011',
    name: '供应商A',
    owner: '货主A',
    status: '启用',
    contactPerson: '王阳明',
    contactPhone: '13587584785',
    contactAddress: '浙江省杭州市西湖区西湖大道XX路',
    remark: ''
  },
  {
    id: 1,
    code: 'GYS11011',
    name: '供应商A',
    owner: '货主A',
    status: '启用',
    contactPerson: '王阳明',
    contactPhone: '13587584785',
    contactAddress: '浙江省杭州市西湖区西湖大道XX路',
    remark: ''
  },
  {
    id: 1,
    code: 'GYS11011',
    name: '供应商A',
    owner: '货主A',
    status: '启用',
    contactPerson: '王阳明',
    contactPhone: '13587584785',
    contactAddress: '浙江省杭州市西湖区西湖大道XX路',
    remark: ''
  },
])
// 表格列配置
const tableColumns = [
  {prop: 'name', label: '商品名称', minWidth: 120, visible: true},
  {prop: 'code', label: '商品编号', width: 120, minWidth: '120', visible: true},
  {prop: 'barcode', label: '商品条码', width: 120, minWidth: '120', visible: true},
  {prop: 'owner', label: '货主', width: 100, minWidth: '100', visible: true},
  {prop: 'category', label: '分类', width: 100, minWidth: '100', visible: true},
  {prop: 'brand', label: '品牌', width: 100, minWidth: '100', visible: true},
  {prop: 'unit', label: '单位', width: 80, minWidth: '80', visible: true},
  {prop: 'tag', label: '商品标签', width: 100, minWidth: '100', visible: true},
  {prop: 'status', label: '状态', width: 80, minWidth: '80', visible: true},
  {prop: 'batchManage', label: '批次管理', width: 100, minWidth: '100', visible: true},
  {prop: 'composition', label: '序列号管理', width: 100, minWidth: '100', visible: true},
  {prop: 'remark', label: '备注', width: '150', minWidth: '150', visible: true},
  {prop: 'operation', label: '操作', width: '60', minWidth: '160', fixed: 'right', visible: true}
]
// 表格加载状态
const tableLoading = ref(false)

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 50
})

const handleDelete = () => {

}

const imgVisible = ref(false)
const dialogImageUrl = ref('')
const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url;
  imgVisible.value = true
}

onActivated(() => {
  initPageMode()
})

</script>

<style lang="scss" scoped>
.commodity-detail {
  padding: 0;
  background-color: #fff;
  height: 100%;
  display: flex;
  flex-direction: column;

  .commodity-detail-header {
    position: sticky;
    top: 0;
    z-index: 10;
    background-color: #fff;
    padding: 20px;
    height: 64px;
    .title-box {
      height: 24px;
      line-height: 24px;
      padding: 0 10px;
      border-left: 6px solid #409eff;
      border-radius: 2px;
      font-weight: bold;
      font-size: var(--el-font-size-medium);
      color: #1A1A1A;
    }
  }

  .content-wrapper {
    flex: 1;
    overflow: auto;
    padding: 0 20px 20px;
  }

  .form-container {
    margin-top: 10px;

    :deep(.el-select__wrapper ) {
      padding-left: 7px;
      padding-right: 5px;
    }
  }

  .button-container {
    margin-top: 20px;
    text-align: center;
  }

  :deep(.el-upload--picture-card) {
    width: 100px;
    height: 100px;
    line-height: 100px;
  }

  .el-form {
    .el-checkbox {
      margin-right: 10px;
    }

    .el-input {
      vertical-align: middle;
    }
  }

  .el-form-item {
    margin-bottom: 18px;

    :deep(.el-input__inner) {
      height: 28px;
    }

    :deep(.el-upload-list--picture-card .el-upload-list__item) {
      width: 100px;
      height: 100px;
    }
  }


}
</style>